/*
 * @Author: miteng 973203639@qq.com
 * @Date: 2023-12-21 09:19:21
 * @LastEditors: shiweizhen 787632169@qq.com
 * @LastEditTime: 2025-07-11 11:01:36
 * @Description:
 * Copyright (c) 2024-present HBIS Digital Technology Co.,Ltd. All rights reserved.
 */
import { createApp, Directive } from 'vue';
import App from './App.vue';
import router from '@/router';
import { setupStore } from '@/store';
import { customMain } from './framework/main';
import { usePermissionStoreHook } from '@/framework/store/modules/permission';
import { Router } from 'vue-router';

// import NoticeDetail from '@/framework/views/notice/components/noticeDetail.vue'
import { icons, apps } from '@hbisdt-design/icons-vue';
import '@/permission';

// 引入svg注册脚本
import 'virtual:svg-icons-register';

// 国际化
import i18n from '@/framework/lang/index';
import '@/framework/styles/index.scss';

// import 'element-plus/theme-chalk/index.css';
//import 'element-plus/theme-chalk/dark/css-vars.css';

// 使用v-html会造成xss攻击，所以引入该插件，使用v-dompurify-html代替v-html
import VueDOMPurifyHTML from 'vue-dompurify-html';

// import ElementPlus from 'element-plus';
//全局引入
import vue3Cron from 'my-cron-vue3';
import 'my-cron-vue3/lib/vue3Cron.css'; // 引入样式
// 引入自定义组件库
import HbisdtDesign from 'hbisdt-design';
import 'hbisdt-design/dist/index.css';
import '@/framework/styles/theme/index.scss';
import * as directive from '@/directive';

// 项目发布线上之后主题色未生效（不是河钢蓝），重新执行，setTheme修改主题色
import { setTheme } from 'hbisdt-design';

setTheme();
const app = createApp(App);
customMain(app); //
// 自定义指令
Object.keys(directive).forEach(key => {
  app.directive(key, (directive as Record<string, Directive>)[key]);
});
for (const [key, component] of Object.entries({ ...icons, ...apps })) {
  app.component(key, component);
}
// 注册自定义指令 v-prevent-reclick
app.directive('prevent-reclick', {
  beforeMount(el, binding) {
    el.disabled = false; // 初始化时启用按钮
    el.addEventListener('click', () => {
      el.disabled = true; // 点击后禁用按钮
      setTimeout(() => {
        el.disabled = false; // 在指定的时间后重新启用按钮
      }, binding.value || 1000); // 使用 binding.value 来设置等待时间，默认为 1000 毫秒
    });
  },
  unmounted(el) {
    // 组件卸载时移除事件监听器
    el.removeEventListener('click', () => {});
  }
});

// 全局方法
import { getDictionaries } from '@/framework/api/dict';
app.config.globalProperties.$getDictionaries = getDictionaries;
// @ts-expect-error
app.config.globalProperties.isMicroApp =
  window.rawWindow?.__MICRO_APP_BASE_APPLICATION__;

// 与基座进行数据交互
function handleMicroData(router: Router) {
  // @ts-expect-error eventCenterForAppNameVite 是基座添加到window的数据通信对象
  if (window.rawWindow?.eventCenterForAppNameVite) {
    // @ts-expect-error 主动获取基座下发的数据;可在此处获取用户信息
    console.log(
      'child-vite getData:',
      window.rawWindow.eventCenterForAppNameVite.getData()
    );

    // @ts-expect-error 监听基座下发的数据变化
    window.rawWindow.eventCenterForAppNameVite.addDataListener(
      (data: Record<string, unknown>) => {
        console.log('child-vite addDataListener:', data);
        if (data.path && typeof data.path === 'string') {
          const permissionStore = usePermissionStoreHook();
          data.path = data.path.replace(/^#/, '');
          // 当基座下发path时进行跳转
          if (data.path && data.path !== router.currentRoute.value.path) {
            router.push(
              data.path === '/'
                ? (permissionStore.firstPath as string)
                : (data.path as string)
            );
          }
        }
      }
    );

    // 向基座发送数据
    // setTimeout(() => {
    //   window.eventCenterForAppNameVite.dispatch({ myname: 'child-vite' })
    // }, 3000)
  }
}

// 全局挂载
setupStore(app);
app
  .use(router)
  // .use(ElementPlus) HbisdtDesign组件中已经全局注册了，不需要再次注册
  .use(HbisdtDesign)
  .use(i18n)
  .use(vue3Cron)
  .use(VueDOMPurifyHTML)
  .mount('#app');

handleMicroData(router);
// 监听卸载操作
window.addEventListener('unmount', function () {
  app.unmount();
  // @ts-expect-error 卸载所有数据监听函数
  window.rawWindow.eventCenterForAppNameVite?.clearDataListener();
  console.log('微应用child-vite卸载了');
});
